from flask import Flask, session, g
from flask_migrate import Migrate

import config
from blueprints import user_bp, qa_bp
from exts import db, mail
from models import User

app = Flask(__name__)
app.config.from_object(config)

app.register_blueprint(qa_bp)
app.register_blueprint(user_bp)
migrate = Migrate(app, db)
mail.init_app(app)
db.init_app(app)


@app.route('/')
def index():
    return "数据库执行成功"


@app.before_request
def before_request():
    user_id = session.get("user_id")
    if user_id:
        try:
            user = User.query.get(user_id)
            setattr(g, "user", user)
        except:
            setattr(g, "user", None)


@app.context_processor
def context_processor():
    if hasattr(g, "user"):
        return {"user": g.user}
    else:
        return {}


if __name__ == '__main__':
    app.run(debug=True)
